package com.gopay.checkorder.service.task;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;

import javax.annotation.Resource;

import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.common.Result;
import com.gopay.common.exception.GopayException;
import com.gopay.remote.bank.SignInInteractRemoteService;

/**
 * 浦发代扣获取密钥
 * @author jiangxiangjiao
 */
public class SpdbSignInTaskImpl implements Task {

	private final static Logger logger = LoggerFactory.getLogger(SpdbSignInTaskImpl.class);

	@Resource(name = "keyPathConfig")
	private Map<String, String> keyPathConfig;

	@Resource(name = "bankSignInClient")
	private SignInInteractRemoteService bankSignInClient;

	@Override
	public void doTask() {
		Thread thread =new Thread(new Runnable() {
			public void run() {
				BufferedWriter bw = null;
				logger.error("download sign start!");
				try {
					Result result = bankSignInClient.signIn(null);
					if (result.isSuccess()) {
						String keyValue = (String) result.getDefaultModel();
						logger.error(new DateTime().toString("YYYYMMdd hh:mm:ss") + "-浦发代扣签到返回密钥为：" + keyValue);
						String path = keyPathConfig.get("locpath");
						File file = new File(path);
						if(!file.exists()){
							file.createNewFile();
						}
						bw = new BufferedWriter(new FileWriter(file));
						bw.write(keyValue);
					} else {
						logger.info(new DateTime().toString("YYYYMMdd hh:mm:ss") + "浦发代扣签到获取密钥失败,不做任何操作");
					}
					logger.error("download sign end!");
				} catch (GopayException e) {
					logger.error("浦发代扣获取密钥异常",e);
				} catch (IOException e) {
					logger.error("浦发代扣签到,创建密钥文件异常");
					e.printStackTrace();
				}finally{
					if(bw != null){
						try {
							bw.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
		});
		thread.start();
		/*BufferedWriter bw = null;
		logger.error("download sign start!");
		try {
			Result result = bankSignInClient.signIn(null);
			if (result.isSuccess()) {
				String keyValue = (String) result.getDefaultModel();
				logger.error(new DateTime().toString("YYYYMMdd hh:mm:ss") + "-浦发代扣签到返回密钥为：" + keyValue);
				String path = keyPathConfig.get("locpath");
				File file = new File(path);
				if(!file.exists()){
					file.createNewFile();
				}
				bw = new BufferedWriter(new FileWriter(file));
				bw.write(keyValue);
			} else {
				logger.info(new DateTime().toString("YYYYMMdd hh:mm:ss") + "浦发代扣签到获取密钥失败,不做任何操作");
			}
			logger.error("download sign end!");
		} catch (GopayException e) {
			logger.error("浦发代扣获取密钥异常",e);
		} catch (IOException e) {
			logger.error("浦发代扣签到,创建密钥文件异常");
			e.printStackTrace();
		}finally{
			if(bw != null){
				try {
					bw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}*/
	}

}

